package com.daffodil.demo.controller;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.daffodil.core.entity.JsonResult;
import com.daffodil.util.JacksonUtils;
import com.daffodil.util.StringUtils;

import cn.hutool.http.HttpUtil;
import io.swagger.annotations.Api;
import reactor.core.publisher.Mono;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 
 * @author yweijian
 * @date 2023年1月4日
 * @version 2.0.0
 * @description
 */
@Api(value = "第三方应用授权登录管理", tags = "第三方应用授权登录管理")
@RestController
@RequestMapping("/api-demo/oauth")
public class OauthController {

    /** 应用ID */
    private String appId = "40280981857b0d7501857b12e84a0000";

    /** 应用秘钥 */
    private String appSecret = "f4f901b26672ed17b21bdf63c5b0b73c6e43ead9d8e4671e2ff0fe4e300ba572cd9f5a7d9360d6a63e52b26f76651fa299e4f5799877246b8fb0e2fec19e2154";

    @GetMapping("/callback")
    public Mono<JsonResult> callback(String code, @ApiIgnore ServerHttpRequest request) throws NoSuchAlgorithmException{
        Map<String, Object> result = new HashMap<String, Object>();
        JsonResult jsonResult = this.getAccessToken(appId, code);
        result.put("token", jsonResult.getData(Map.class));
        String accessToken = (String) jsonResult.getData(Map.class).get("accessToken");
        String url = StringUtils.format("http://127.0.0.1:49101/api-auth/oauth/user?access_token={}", accessToken);
        String body = HttpUtil.get(url);
        JsonResult json = JacksonUtils.toJavaObject(body, JsonResult.class);
        result.put("user", json.getData(Map.class));
        return Mono.just(JsonResult.success(result));
    }

    /**
     * -根据授权码获取认证令牌
     * @param appId
     * @param code
     * @return
     */
    private JsonResult getAccessToken(String appId, String code) {
        String url = StringUtils.format("http://127.0.0.1:49101/api-auth/oauth/token?appId={}&appSecret={}&code={}", appId, appSecret, code);
        //{msg=操作成功, code=0, data={accessToken=d827b885-56e4-45dd-8b22-c8a1449e117d, expireTime=1800, refreshToken=a1159cfe-b56a-4988-ae17-3eb5ec308783, createTime=2023-04-28 11:32:52}}
        String body = HttpUtil.get(url);
        return JacksonUtils.toJavaObject(body, JsonResult.class);
    }
}
